package com.osell.selection.ui.common;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebSettingsImpl;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.ui.base.BaseFragment;
import com.osell.selection.util.DeviceUuidFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.HttpUrl;

public class WebViewFragment extends BaseFragment {

    @BindView(R.id.web_view_container)
    LinearLayout web_view_container;

    private Unbinder mUnBinder;
    private Disposable mDisposable;

    private AgentWeb mAgentWeb;

    private String mUrl;

    public static WebViewFragment newInstance(String url) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle args = new Bundle();
        args.putString("url", url);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mUrl = args.getString("url");
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            if (!mUserInfoSp.getBoolean("signed_in", false)) {
                if (url.contains("Member-reurl")) {
                    HttpUrl httpUrl = HttpUrl.parse(url);
                    if (httpUrl != null) {
                        if (mDisposable != null) {
                            mDisposable.dispose();
                        }
                        mDisposable = RestAPI.getInstance().oSellService()
                                .getSignedInInfo(httpUrl.queryParameter("opdid"))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(signedInInfoResponseData -> {
                                    if (TextUtils.equals("000000", signedInInfoResponseData.code)) {
                                        mUserInfoSp
                                                .edit()
                                                .putBoolean("signed_in", true)
                                                .putString("user_id", signedInInfoResponseData.data.id)
                                                .putString("user_key", signedInInfoResponseData.data.userKey)
                                                .apply();
                                    } else {
                                        Toast.makeText(MyApplication.getInstance(), signedInInfoResponseData.message, Toast.LENGTH_SHORT).show();
                                    }
                                }, throwable -> Toast.makeText(MyApplication.getInstance(), throwable.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                }
            }
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_web_view, container, false);
        mUnBinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        String deviceId = new DeviceUuidFactory(MyApplication.getInstance()).getDeviceUuid().toString();
        String language = MyApplication.getInstance().getResources().getConfiguration().locale.getLanguage();
        if (TextUtils.equals("zh", language)) {
            language = "cn";
        }

        HttpUrl httpUrl = HttpUrl.parse(mUrl);
        mAgentWeb = AgentWeb.with(this) // 传入Activity
                .setAgentWebParent(web_view_container,
                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT)) // 传入AgentWeb的父控件
                .useDefaultIndicator() // 使用默认进度条
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setAgentWebWebSettings(new AgentWebSettingsImpl() {
                    @Override
                    public WebSettings getWebSettings() {
                        WebSettings webSettings = super.getWebSettings();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            webSettings.setAllowFileAccessFromFileURLs(true);
                            webSettings.setAllowUniversalAccessFromFileURLs(true);
                        }
                        return webSettings;
                    }
                })
                .createAgentWeb()
                .ready()
                .go(httpUrl == null ? "" : httpUrl
                        .newBuilder()
                        .addQueryParameter("id", mUserInfoSp.getString("user_id", ""))
                        .addQueryParameter("user_id", mUserInfoSp.getString("user_id", ""))
                        .addQueryParameter("user_key", mUserInfoSp.getString("user_key", ""))
                        .addQueryParameter("deviceId", deviceId)
                        .addQueryParameter("deviceType", "1")
                        .addQueryParameter("device_id", deviceId)
                        .addQueryParameter("device_type", "1")
                        .addQueryParameter("lan", language)
                        .build()
                        .toString());
    }

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroyView();
        mUnBinder.unbind();
    }
}
